var mongoose = require('./db.js')
var Schema = mongoose.Schema
var CodeSchema = new Schema({
  codename: { type: String }, //代码标题
  codeintro: { type: String }, //代码简介
  codetype: { type: String }, //代码类型
  codecontent: { type: String } //代码内容
})
var Code = mongoose.model('Code', CodeSchema)

function saveCode(data) {
  var code = new Code({
    codename: data.codename,
    codeintro: data.codeintro,
    codetype: data.codetype,
    codecontent: data.codecontent
  })
  var callbackObj = new Promise(function(resolve, reject) {
    code.save(function(err, res) {
      if (err) {
        console.log(reject, '数据库错误')
        reject(err)
      } else {
        console.log(resolve, '操作成功')
        resolve(res)
      }
    })
  })
  return callbackObj;
}

function findCode() {
  var callbackObj = new Promise(function(resolve, reject) {
    Code.find({},function(err, res) {
      if (err) {
        console.log(reject, '数据库错误')
        reject(err)
      } else {
        console.log(resolve, '操作成功')
        resolve(res)
      }
    })
  })
  return callbackObj;
}

module.exports = {
  saveCode: saveCode,
  findCode: findCode
}